package com.medical.client.controller.personal;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.medical.client.controller.RootController;
import com.medical.client.controller.utils.HttpUtils;
import com.medical.client.controller.utils.LoadingUtils;
import com.medical.client.model.Context;
import com.medical.client.model.Personal;
import javafx.application.Platform;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.CheckBox;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextArea;
import javafx.scene.control.cell.CheckBoxTableCell;
import javafx.scene.control.cell.PropertyValueFactory;

/**
 * @ClassName: PersonalBorderController
 * @Description: TODO
 * @Author: JackyLee
 * @Date: 2024/6/3 22:20
 **/
public class BorderController extends RootController {
    @FXML
    private TableView<Personal> tableView;

    @FXML
    private TableColumn<Personal, String> tjserial;

    @FXML
    private TableColumn<Personal, String> cjserial;

    @FXML
    private TableColumn<Personal, String> name;

    @FXML
    private TableColumn<Personal, String> sex;

    @FXML
    private TableColumn<Personal, String> age;

    @FXML
    private TableColumn<Personal, String> unitname;

    @FXML
    private TableColumn<Personal, Boolean> selectedColumn;

    @FXML
    private TextArea ta;

    private ObservableList<Personal> items;

    @FXML
    private CheckBox allCheck;

    @FXML
    protected void allSelect() {
        if (allCheck.isSelected()) {
            items.forEach(item -> item.setSelectedProperty(true));
        } else {
            items.forEach(item -> item.setSelectedProperty(false));
        }
    }


    @FXML
    private void initialize() {
        tjserial.setCellValueFactory(new PropertyValueFactory<>("tjserial"));
        cjserial.setCellValueFactory(new PropertyValueFactory<>("cjserial"));
        name.setCellValueFactory(new PropertyValueFactory<>("name"));
        sex.setCellValueFactory(new PropertyValueFactory<>("sex"));
        age.setCellValueFactory(new PropertyValueFactory<>("age"));
        unitname.setCellValueFactory(new PropertyValueFactory<>("unitname"));
        selectedColumn.setCellValueFactory(cellData -> cellData.getValue().selectedProperty());
        selectedColumn.setCellFactory(CheckBoxTableCell.forTableColumn(selectedColumn));

        //初始化表格和监听事件
        items = FXCollections.observableArrayList();
        //list添加值对象
        tableView.setItems(items); //tableview添加list
        tableView.setEditable(true);

        // 添加监听器以响应复选框的变化
        selectedColumn.setCellFactory(tc -> {
            CheckBoxTableCell<Personal, Boolean> cell = new CheckBoxTableCell<>();
            cell.setSelectedStateCallback(index -> {
                if (index >= 0 && index < items.size()) {
                    System.out.println(items.get(index).getUnitname() + "==" + items.get(index).selectedProperty());
                    return items.get(index).selectedProperty();
                } else {
                    System.out.println("yyyyy");
                    return new SimpleBooleanProperty(false);
                }
            });
            return cell;
        });
    }

    public void setData(String demc, String tjh, String jcls,String startDate, String endDate, boolean isSelect) {
        tableView.getItems().clear();
        Platform.runLater(() -> {
            // 更新UI的代码
            LoadingUtils.show();
            GridController functionController = (GridController) Context.controllers.get("com.medical.client.controller.personal.GridController");
            functionController.setBtu(true);
            tableView.setDisable(true);
        });

        JsonObject paraJson = new JsonObject();
        paraJson.addProperty("demc", demc);
        paraJson.addProperty("tjh", tjh);
        paraJson.addProperty("jcls", jcls);
        paraJson.addProperty("startDate", startDate);
        paraJson.addProperty("endDate", endDate);
        paraJson.addProperty("isCheck", isSelect?1:0);

        String result = HttpUtils.sendPostRequest("http://127.0.0.1:9009/api/wh/external/queryPersonal",paraJson.toString());
        JsonObject jsonResult = JsonParser.parseString(result).getAsJsonObject();

        if(jsonResult!=null){
            if(jsonResult.get("data")!=null){
                JsonArray jsonArray = jsonResult.getAsJsonArray("data");
                for (int i=0;i<jsonArray.size();i++){
                    JsonObject jsonObject = jsonArray.get(i).getAsJsonObject();
                    Personal unitTable = new Personal();
                    unitTable.setUnitname(jsonObject.get("unitname").getAsString());
                    unitTable.setAge(jsonObject.get("age").getAsString());
                    unitTable.setName(jsonObject.get("name").getAsString());
                    unitTable.setSex(jsonObject.get("sex").getAsString());
                    unitTable.setCjserial(jsonObject.get("cjserial").getAsString());
                    unitTable.setTjserial(jsonObject.get("tjserial").getAsString());
                    items.add(unitTable);
                }
            }
        }

        Platform.runLater(() -> {
            // 更新UI的代码
            LoadingUtils.close();
            GridController functionController = (GridController) Context.controllers.get("com.medical.client.controller.personal.GridController");
            functionController.setBtu(false);
            tableView.setDisable(false);
        });
    }

    public void uploadData(){
        // 遍历items，获取选中的数据，并上传到服务器
        Platform.runLater(() -> {
            // 更新UI的代码
            LoadingUtils.show();
            com.medical.client.controller.unit.GridController functionController = (com.medical.client.controller.unit.GridController) Context.controllers.get("com.medical.client.controller.unit.GridController");
            functionController.setBtu(true);
            tableView.setDisable(true);
            tableView.getItems().clear();
        });

        try {
            // 遍历items，获取选中的数据，并上传到服务器
            StringBuffer stringBuffer = new StringBuffer();
            items.forEach(item->{
                if(item.selectedProperty().getValue()){
                    JsonObject jsonObject = new JsonObject();
                    jsonObject.addProperty("tjserial",item.getTjserial());

                    String result = HttpUtils.sendPostRequest("http://127.0.0.1:9009/api/wh/external/person",jsonObject.toString());

                    JsonObject jsonResult = JsonParser.parseString(result).getAsJsonObject();
                    String data = jsonResult.get("data").getAsString();
                    stringBuffer.append(data);
                    stringBuffer.append("\n");
                    ta.setText(stringBuffer.toString());
                }
            });
        }catch (Exception e){
            e.printStackTrace();
        }

        Platform.runLater(() -> {
            // 更新UI的代码
            LoadingUtils.close();
            com.medical.client.controller.unit.GridController functionController = (com.medical.client.controller.unit.GridController) Context.controllers.get("com.medical.client.controller.unit.GridController");
            functionController.setBtu(false);
            tableView.setDisable(false);
        });
    }

    public void clearData() {
        tableView.getItems().clear();
        ta.clear();
    }
}